package com.megastudyletsthi;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.hocmai.json.request.SendJsonLogin;
import com.hocmai.save.preference.PreferenceConnector;

public class HocmaiLoginActivity extends Activity {

	private Button login, signIn;
	private EditText userName, password;
	private CheckBox cBoxSave;
	private ProgressDialog progressDialog;
	// set URL_LOGIN at here
	private static String URL_LOGIN = "http://megatest.com.vn/request_user.php";

	// JSON Node User Account.
	private static final String TAG_USER = "user"; // array user content
	private static final String TAG_SIGNAL = "signal"; // return signal 1 | 0
	private static final String TAG_NAME = "name"; // get user name
	private static final String TAG_POINT = "point"; // score user
	private static final String TAG_LEVEL = "level"; // level of user into app
	private static final String TAG_AVATAR = "avatar"; // Avatar of user

	// JSON Node Info user
	private static final String TAG_INFO_USER = "info_user"; // array info user
	private static final String TAG_SCHOOL = "school"; // school of user
	private static final String TAG_PHONE = "phone"; // phone number of user.

	String signal = null;
	String name = null;
	String point = null;
	String level = null;
	String avatar = null;
	

	SendJsonLogin sendJsonLogin = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);

		this.login = (Button) findViewById(R.id.btn_login);
		this.signIn = (Button) findViewById(R.id.btn_sign_in);
		this.userName = (EditText) findViewById(R.id.editTextName);
		this.password = (EditText) findViewById(R.id.editPassWord);
		this.cBoxSave = (CheckBox) findViewById(R.id.checkbox_save_user);

		readPerson();
		// Check network.
		checkNetworkStatus();

		this.login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String name = userName.getText().toString();
				String pass = password.getText().toString();

				if (name.length() == 0 & pass.length() == 0) {
					Toast.makeText(HocmaiLoginActivity.this,
							"Bạn chưa nhập tên và password !",
							Toast.LENGTH_LONG).show();
				} else if (isOnline() == true) {
					progressDialog = new ProgressDialog(
							HocmaiLoginActivity.this);
					progressDialog.setTitle("Xin chờ !");
					progressDialog.setMessage("Đang đang nhập !");
					progressDialog.show();
					new Asyn().execute("1");
				} else {
					Toast.makeText(HocmaiLoginActivity.this,
							"Lỗi kết nối tới máy chủ", Toast.LENGTH_LONG)
							.show();
				}
			}
		});

		signIn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(HocmaiLoginActivity.this,
						HocmaiSignInActivity.class);
				startActivity(intent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_hocmai_login, menu);
		return true;
	}

	// Checking internet connected
	public void checkNetworkStatus() {

		final ConnectivityManager connMgr = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		final android.net.NetworkInfo wifi = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		final android.net.NetworkInfo mobile = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		if (wifi.isAvailable()) {

			Toast.makeText(this, "Bạn đang sử dụng Wifi", Toast.LENGTH_LONG)
					.show();
		} else if (mobile.isAvailable()) {

			Toast.makeText(this, "Bạn đang sử dụng 3G ", Toast.LENGTH_LONG)
					.show();
		} else {
			Toast.makeText(this,
					"Lỗi kết nối mạng ! Vui lòng bật kết nối Internet. ",
					Toast.LENGTH_LONG).show();
		}
	}

	// check connect to internet.
	public boolean isOnline() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		return (networkInfo != null && networkInfo.isConnected());
	}
	/*
	 * Send login request to sever do in background
	 */
	class Asyn extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String name = userName.getText().toString();
			String pass = password.getText().toString();
			MD5 md5 = new MD5();
			sendJsonLogin = new SendJsonLogin();
			try {
				sendJsonLogin.sendJsonLogin(name, md5.getMD5(pass), URL_LOGIN);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			// ////////////////////////////////////////
			try {
				getLoginSignal();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			
			if (signal.equals("1")) {
				Intent intent = new Intent(HocmaiLoginActivity.this, HocmaiMainWorkActivity.class);
				startActivity(intent);
			} else if (signal.equals("0")) {
				Toast.makeText(HocmaiLoginActivity.this, "Sai tên hoặc mật khẩu !",
						Toast.LENGTH_LONG).show();
			}
//			Toast.makeText(HocmaiLoginActivity.this, sendJsonLogin.DATA, Toast.LENGTH_LONG).show();
		}
	}

	public void getLoginSignal() throws JSONException {
		try {
			// Parse the data into jsonobject to get original data in form of
			// json.
			JSONObject jObject = new JSONObject(sendJsonLogin.DATA);
			JSONArray jArray = jObject.getJSONArray(TAG_USER);
			// ArrayList<String[]> data = new ArrayList<String[]>();
			for (int i = 0; i < jArray.length(); i++) {
				signal = jArray.getJSONObject(i).getString(TAG_SIGNAL);
				if (signal.equals("1")) {
					// name = jArray.getJSONObject(i).getString(TAG_NAME);
					// point = jArray.getJSONObject(i).getString(TAG_POINT);
					// level = jArray.getJSONObject(i).getString(TAG_LEVEL);
					// avatar = jArray.getJSONObject(i).getString(TAG_AVATAR);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	 * save id, pass to memory
	 */
	public void save(View view) {
		String nameText = userName.getText().toString();
		String passText = password.getText().toString();

		if (nameText != null)
			PreferenceConnector.writeString(this, PreferenceConnector.NAME,
					nameText);
		if (passText != null)
			PreferenceConnector.writeString(this, PreferenceConnector.PASS,
					passText);
	}

	public void reset(View view) {
		/*
		 * A better way to delete all is:
		 * PreferenceConnector.getEditor(this).clear().commit();
		 */
		PreferenceConnector.getEditor(this).remove(PreferenceConnector.NAME)
				.commit();
		PreferenceConnector.getEditor(this).remove(PreferenceConnector.PASS)
				.commit();
		readPerson();
	}

	/*
	 * Read the data refer to saved person and visualize them into Edittexts
	 */
	private void readPerson() {
		userName.setText(PreferenceConnector.readString(this,
				PreferenceConnector.NAME, null));
		password.setText(PreferenceConnector.readString(this,
				PreferenceConnector.PASS, null));
	}

}
